package webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {

	private Socket socket;
	private InputStream in;
	private PrintStream out;

	public static final String webroot = "C:\\image\\";

	public Processor(Socket socket)

	{
		this.socket = socket;

		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	public void run()

	{

		String filename = parse(in);

		SendFile(filename);

	}

	public String parse(InputStream in)

	{

		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;
		try {
			String httpmessage = br.readLine();

			String[] content = httpmessage.split(" ");

			if (content.length != 3) {

				SendErrorMessage(400, "client query error");
				return null;
			}

			System.out.println("code:" + content[0] + ",filename:" + content[1]
					+ ",version:" + content[2]);

			filename = content[1];
		} catch (IOException e) {

			e.printStackTrace();
		}

		return filename;

	}

	public void SendErrorMessage(int errorcode, String errorMessage) {

		out.println("HTTP/1.0" + errorcode + " " + errorMessage);
		out.println("content-type:text/html");
		out.println("");
		out.println("<html>");

		out.println("<title>ERROR MESSAGE:");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>error message:" + errorcode + " " + errorMessage+"</h1>");
		out.println("</body>");		
		

		out.println("</html>");

	}

	public void SendFile(String filename) {

		File file = new File(this.webroot + filename);

		if (!file.exists()) {
			SendErrorMessage(404, "file not found!");
		} else {

			try {
				InputStream in = new FileInputStream(file);

				byte content[] = new byte[(int) file.length()];
				try {
					in.read(content);

					out.println("HTTP/1.0 200 responsefile");
					out.println("content-length" + content.length);
					out.println("");
					out.write(content);
					out.flush();
					out.close();
					in.close();

				} catch (IOException e) {

					e.printStackTrace();
				}

			} catch (FileNotFoundException e) {

				e.printStackTrace();
			}

		}

	}

}
